﻿using System;
using System.IO.Ports;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace RS_232
{
    public partial class Form1 : Form
    {
        private SerialPort _serialPort = new SerialPort();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // 初始化波特率
            cmbBaudRate.Items.AddRange(new object[] { 9600, 19200, 115200 });
            cmbBaudRate.SelectedItem = 9600;

            // 初始化停止位
            cmbStopBits.Items.Add(StopBits.One);
            cmbStopBits.Items.Add(StopBits.Two);
            cmbStopBits.SelectedItem = StopBits.One;

            // 配置串口事件
            _serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

            // 初始化COM端口列表
            RefreshSerialPortList();
        }

        private void RefreshSerialPortList()
        {
            cmbPort.Items.Clear();
            foreach (string port in SerialPort.GetPortNames())
            {
                cmbPort.Items.Add(port);
            }
            if (cmbPort.Items.Count > 0)
            {
                cmbPort.SelectedIndex = 0; // 默认选第一个端口
            }
            else
            {
                MessageBox.Show("未检测到可用的COM端口！");
            }
        }

        private void btnOpenPort_Click(object sender, EventArgs e)
        {
            // 刷新串口列表
            RefreshSerialPortList();

            if (_serialPort.IsOpen)
            {
                _serialPort.Close();
                btnOpenPort.Text = "打开串口";
            }
            else
            {
                // 检查控件是否为空
                if (cmbPort.SelectedItem == null)
                {
                    MessageBox.Show("请选择COM端口！");
                    return;
                }
                if (cmbBaudRate.SelectedItem == null)
                {
                    MessageBox.Show("请选择波特率！");
                    return;
                }
                if (cmbStopBits.SelectedItem == null)
                {
                    MessageBox.Show("请选择停止位！");
                    return;
                }

                // 配置并打开串口
                try
                {
                    _serialPort.PortName = cmbPort.SelectedItem.ToString();
                    _serialPort.BaudRate = Convert.ToInt32(cmbBaudRate.SelectedItem);

                    // 添加类型检查
                    if (cmbStopBits.SelectedItem is StopBits stopBits)
                    {
                        _serialPort.StopBits = stopBits;
                    }
                    else
                    {
                        MessageBox.Show("停止位选择无效，请重新选择！");
                        return;
                    }

                    _serialPort.Parity = Parity.None;
                    _serialPort.DataBits = 8;

                    _serialPort.Open();
                    btnOpenPort.Text = "关闭串口";
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"打开串口失败：{ex.Message}");
                }
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (!_serialPort.IsOpen)
            {
                MessageBox.Show("请先打开串口！");
                return;
            }

            string message = txtSend.Text.Trim();
            if (string.IsNullOrEmpty(message))
                return;

            // 添加发送时间戳
            string sentMessage = $"[SENT {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] {message}";
            rtbSendLog.AppendText($"→ {sentMessage}\n");
            txtSend.Clear();

            // 发送数据
            _serialPort.WriteLine(sentMessage);
        }

        private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            if (_serialPort == null || !_serialPort.IsOpen)
                return;

            // 异步接收数据
            string receivedData = _serialPort.ReadExisting();
            string formattedData = $"[RECV {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}] {receivedData}";

            // 在接收日志中显示（需通过Invoke更新UI）
            this.Invoke(new Action(() =>
            {
                rtbReceivelog.AppendText(formattedData);
                rtbReceivelog.ScrollToCaret();
            }));
        }
    }
}